<?php
namespace App\Model;

use App\Entity\User;
use App\JobEntity\JobUser;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * 商品抢购
 * Class GoodsModel
 * @package App\Model\
 */
class GoodsModel
{
    private $container;
    private $jobConn;
    /** @var  \Monolog\Logger */
    private $logger;

    /**
     * GoodsModel constructor.
     * @param ContainerInterface $container
     * @param $logger
     */
    public function __construct($container, $logger)
    {
        $this->container = $container;
        $this->jobConn = $container->get('doctrine.dbal.customer_connection');
        $this->logger = $logger;
    }

    /**
     * 获取所有商品
     * @return array
     */
    public function getGoodsList()
    {
        try{
            $list = $this->jobConn->fetchAll("select goods_name,id from app_goods order by id");

            return array('code' => 0, 'data' => $list);
        } catch (\Exception $e) {
            $this->logger->error(sprintf("查询商品失败，失败原因【%s】", $e->getMessage()));

            return array('code' => 500, 'message' => "查询失败");
        }
    }

    /**
     * 获取商品属性
     * @param $goodsId
     * @return array
     */
    public function getGoodsAttr($goodsId)
    {
        if (empty($goodsId)) {
            return array('code' => 400, 'message' => "商品ID不存在");
        }
        $key = "fkl.goods.".$goodsId;
        $redis = $this->container->get('snc_redis.default');
        $goodsData = $redis->hgetall($key);
        if (empty($goodsData)) {
            $goodsData = $this->jobConn->fetchAssoc("select goods_name,id,goods_num from app_goods where id=:id", array('id' => $goodsId));
            $redis->hmset($key, $goodsData);
            //$redis->expire($key, 24*3600*2);
        }

        return array('code' => 0, 'data' => $goodsData);
    }

    /**
     * 抢购
     * @param JobUser $user
     * @param $goodsId
     * @return array
     */
    public function snapUp($user, $goodsId)
    {
        try {
            $orderData['user_id'] = $userId = $user->getId();
            $orderData['username'] = $user->getUsername();
            if (empty($goodsId)) {
                return array("code" => 400, "message" => "商品ID不存在");
            }
            $key = "fkl.goods.".$goodsId;
            $maxOrders = $this->container->getParameter("my.config");
            $redis = $this->container->get('snc_redis.default');
            for ($i = 0; $i < $maxOrders['maxOrders']; $i++) {
                $goodsNum = $redis->hget($key, "goods_num");
                if ($goodsNum >0 ){
                    $redis->hincrby($key, 'goods_num', -1);
                    $orderData['order_id'] = $this->createUnique();
                    $orderData['goods_id'] = $goodsId;
                    $orderData['start_time'] = date("Y-m-d H:i:s", time());
                    $this->container->get('commen_mq')->writeMq($orderData, 'FKL');
                } else {
                    $redis->del(array($key));
                    return array("code" => 401, "message" => "抱歉已经抢完 成功抢购".$i."个");
                }
            }
            $goodsNum = $redis->hget($key, "goods_num");
            return array('code' => 0, 'data' => array('goods_num' => $goodsNum, "snap_num" => $maxOrders['maxOrders']));

        } catch (\Exception $e) {
            return array("code" => 500, "message" => "抢购失败");
        }
    }

    /**
     * 导出
     * @param JobUser $user
     * @return array
     */
    public function createExport($user)
    {
        $userId = $user->getId();
        $userName = $user->getUsername();
        $type = 0;
        $rate = 0;
        $exportType = 2;
        try {
            $where = " username=:username ";
            $condition = array("username" => $userName);
            $count = $this->jobConn->fetchColumn("select count(*) from app_order where $where", $condition);
            $maxId = $this->jobConn->fetchColumn("select max(id) from app_order");
            //插入数据
            $this->jobConn->insert(
                "app_export",
                array(
                    "user_id" => $userId,
                    "username" => $userName,
                    "type" => $type,
                    "rate" => $rate,
                    "count" => $count,
                )
            );
            $exportId = $this->jobConn->lastInsertId();
            $where .= " and id<=:id";
            $condition["id"] = $maxId;
            $title = array(
                "id" => array(
                    "name" => "ID",
                    "type" => "int",
                ),
                "goods_name" => array(
                    "name" => "商品名称",
                    "type" => "string",
                ),
                "username" => array(
                    "name" => "用户名称",
                    "type" => "string",
                ),
                "buy_num" => array(
                    "name" => "购买数量",
                    "type" => "int",
                ),
                "start_time" => array(
                    "name" => "时间",
                    "type" => "string",
                ),
                "is_del" => array(
                    "name" => "订单状态",
                    "type" => "string",
                ),
                "order_id" => array(
                    "name" => "订单号",
                    "type" => "string",
                ),
            );
            $sql = $this->interpolateQuery("select * from app_order WHERE $where", $condition);
            $data = array(
                "title" => $title,
                "sql" => $sql,
                "export_id" => $exportId,
                "export_type" => $exportType,
                "file_name" => $userName.time(),
                "count" => $count,
            );
            $this->container->get('commen_mq')->writeMq($data, 'FKL2');

            return array('code' => 0, "message" => "任务创建成功");
        } catch (\Exception $e) {

            return array("code" => 500, "message" => "导出失败");
        }
    }

    /**
     * 获取随机数
     * @return string
     */
    function createUnique() {
        $data = $_SERVER['HTTP_USER_AGENT'].$_SERVER['REMOTE_ADDR'].time().rand();

        return md5($data);
        //return md5(time().$data);
    }

    /**
     *
     * @param string $query
     * @param array $params
     * @return mixed
     */
    public function interpolateQuery($query, $params)
    {
        $keys = array();
        foreach ($params as $key => $value) {
            if (is_string($key)) {
                $keys[] = '/:'.$key.'/';
            } else {
                $keys[] = '/[?]/';
            }
            $params[$key] = "'".$value."'";
        }

        $query = preg_replace($keys, $params, $query, 1, $count);

        return $query;
    }
}